package com.ala4.oxcafe.boot.utils;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.BlockingQueue;

/**
 * 线程池工具类
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/4 10:31
 */
public class ThreadPoolUtil {

    private ThreadPoolUtil() {
    }

    /**
     * 判断线程池是否可以提交新任务
     *
     * @param executor 线程池实例
     * @return true=可以提交, false=不可提交（将触发拒绝策略）
     */
    public static boolean canAcceptTask(ThreadPoolTaskExecutor executor) {
        if (executor == null || executor.getThreadPoolExecutor().isShutdown()) {
            return false;
        }

        // 获取底层 ThreadPoolExecutor 和任务队列
        BlockingQueue<Runnable> queue = executor.getThreadPoolExecutor().getQueue();
        int poolSize = executor.getThreadPoolExecutor().getPoolSize();
        int maxPoolSize = executor.getMaxPoolSize();
        int queueCapacity = executor.getQueueCapacity();

        // 情况1：当前线程数 < 最大线程数 → 可直接创建新线程处理任务
        if (poolSize < maxPoolSize) {
            return true;
        }

        // 情况2：队列未满 → 任务可入队等待
        // 注意：队列容量为Integer.MAX_VALUE时视为无界队列
        if (queueCapacity <= 0) { // 无界队列
            return true;
        } else {
            return queue.size() < queueCapacity;
        }
    }

    // 扩展方法：获取线程池负载详情
    public static String getPoolStats(ThreadPoolTaskExecutor executor) {
        return String.format(
                "Pool: %d/%d threads, Queue: %d/%d tasks",
                executor.getActiveCount(),
                executor.getMaxPoolSize(),
                executor.getThreadPoolExecutor().getQueue().size(),
                executor.getQueueCapacity()
        );
    }
}
